package minesweeper;

import interfaces.Minesweepable;

class FlaggedMinesweeper {
	private int minesLeft;
	private int flagsLeft;
	private boolean[][] isFlaggedSquare;
	private Minesweepable minesweeper;
	
	int flagsLeft() {
		return this.flagsLeft;
	}
	
	boolean isAllFlagsCorectlyPlaced() {
		return this.flagsLeft == 0 && this.minesLeft == 0;
	}

	boolean isFlaggedSquare(int row, int column) {
		return this.isFlaggedSquare[row][column];
	}

	private FlaggedMinesweeper(Minesweepable minesweeper, int row, int column, int numberOfMines) {
		this.minesweeper = minesweeper;
		this.isFlaggedSquare = new boolean[row][column];
		this.minesLeft = numberOfMines;
		this.flagsLeft = this.minesLeft;
	}

	static FlaggedMinesweeper createFlaggedMinesweeper(
			Minesweepable minesweeper, int row, int column, int numberOfMines) {
		if (minesweeper != null && row > 0 && column > 0)
			return new FlaggedMinesweeper(minesweeper, row, column, numberOfMines);
		else
			return null;
	}

	void changeFlagSquareState(int row, int column) {
		if (isValidExistaintSquare(row, column)) {
			if (!this.isFlaggedSquare(row, column)) 
				updateMinesValidation(row, column, -1);
			else
				updateMinesValidation(row, column, 1);

			this.isFlaggedSquare[row][column] = !isFlaggedSquare[row][column];
		}
	}

	private void updateMinesValidation(int row, int column, int updateWith) {
		if (updateWith == 1 || updateWith == -1) {
			this.flagsLeft += updateWith;
			if (this.minesweeper.getSquare(row, column) == -1)
				this.minesLeft += updateWith;
		}
	}

	private boolean isValidExistaintSquare(int row, int column) {
		return row >= 0 && column >= 0 && row < isFlaggedSquare.length
				&& column < isFlaggedSquare[row].length;
	}
}